<template>
  <div class="login">
    <div class="title">登录页</div>
    <van-form @submit="login">
      <van-field
        class="input-box"
        v-model="formData.phone"
        placeholder="输入手机号"
        :rules="[{ required: true, pattern:/^1[3-9]\d{9}$/,message: '请输入手机号' }]"
      />
      <van-field
      class="input-box"
        v-model="formData.pass"
        type="password"
        placeholder="输入密码"
        :rules="[{ required: true, pattern:/^\d{6}$/, message: '请输入密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <button round block @click="reguster" class="zhuce" >点此注册新账号</button>
  </div>
</template>

<script>

// 导入组件
import { Toast } from 'vant';
import {user_login} from '../utils/api'

export default {
  data(){
    return {
      formData:{
        phone:'',
        pass:'',
      }
    }
  },
  methods:{
    login(){
      // 发起登录请求
      user_login( this.formData ).then((res)=>{
        if( res.data.code == 200 ){
          //保存用户信息,token
          localStorage.setItem('token',res.data.token);
          localStorage.setItem('userinfo', JSON.stringify( res.data.userinfo ) );


          // 每次登录成功则记录登录时间
          localStorage.setItem('loginTime',Date.parse(new Date()));
          // 六小时登录有效期设置
          var loginTime = localStorage.getItem('loginTime')
          // console.log(loginTime);
          console.log(Date.parse(new Date()));
          // 时间戳大小 十秒1000 ，一分钟：60000 ， 六小时：21600000
          var timer ;
          timer = setInterval(()=>{
            // 当前时间
            var nowTime = Date.parse(new Date());
            // 当前时间减去登录时间
            var intervalTime = nowTime - loginTime;
            if(intervalTime >= 21600000){
              localStorage.removeItem('token');
              // 跳转到登录页
              this.$router.push('/login');
              clearInterval(timer);
            }
          },3600000);

          //自动跳转到首页
          this.$router.push('/');
          Toast.success('登陆成功!')

          // 获取用户的userid，将userid保存在vuex中
          this.$store.commit('add_userid')

          // 请求当前用户的收藏列表
          this.$store.dispatch('request_favlist');

           // 请求当前用户的购物车列表
           this.$store.dispatch('request_shopcarlist');

          //  请求当前用户的地址列表
          this.$store.dispatch('request_address_list');
        }else{
          Toast.fail('登陆失败!')
        }
      })
    },
    reguster(){
      this.$router.push('/register');
    }
  }
}
</script>

<style lang='scss' scoped> 

.login{
  margin: 50px 20px;
}
.login .title{
  font-weight: bold;
  text-align: center;
  line-height: 40px;
  font-size: 32px;
}


.login .input-box{
  border: 1px solid #ccc;
  margin: 30px 0;
  border-radius: 30px;
}

.zhuce{
  position: absolute;
  right: 20px;
  padding: 5px 20px;
  border: none;
  font-size: 14px;
  color: lightblue;
  background-color: white;
}


</style>